<?php

namespace App\Http\Base;

use App\Exceptions\ParamException;
use Illuminate\Support\Facades\Validator;
use Laravel\Lumen\Routing\Controller;

class BaseController extends Controller {

    /**
     * 验证业务参数
     * @param $request
     * @param $module
     * @throws ParamException
     */
    public function validateBusinessParam($request, $module)
    {
        $rules = config('rules.' . $module . '.rules');
        $msg = config('rules.' . $module . '.messages');
        if (!$rules || !$msg) return ;

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($request->paramData, $rules, $msg);
        if ($validator->fails()) {
            $errcodeKey = $validator->messages()->first();
            throw new ParamException($errcodeKey);
        }
    }

    /**
     * 重新格式化加密的参数，因为加密的数据在使用$request获取时候会将+替换为空格，
     * 因此次函数是还原加密参数的原型
     * @param string 加密的字符串
     * @param bool $needDoubleEqual
     * @return string 返回还原了的字符串
     */
    public function formatEncodeParam($encodeStr, $needDoubleEqual = false)
    {
        $encodeStr = str_replace(' ', '+', $encodeStr);
        $encodeStr = !$needDoubleEqual ? $encodeStr : $encodeStr . '==';
        return $encodeStr;
    }
}
